<script setup>
import { useI18n } from "vue-i18n";
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { checkLogin, getQrCode } from "@/api/user";
import { useNav } from "@/layout/hooks/useNav";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { ref, reactive, toRaw, onBeforeUnmount, onBeforeMount } from "vue";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { useIntervalFn } from "@vueuse/core";
import { setToken, removeToken } from "@/utils/auth";

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import globalization from "@/assets/svg/globalization.svg?component";

import Check from "@iconify-icons/ep/check";
defineOptions({
  name: "Login"
});
const router = useRouter();

const { initStorage } = useLayout();
initStorage();

const { t } = useI18n();
const { dataTheme, overallStyle, dataThemeChange } = useDataThemeChange();
dataThemeChange(overallStyle.value);
const { title, getDropdownItemStyle, getDropdownItemClass } = useNav();
const { locale, translationCh, translationEn } = useTranslationLang();
let qrCodeUrl = ref("");
let ticket = ref("");
// 获取二维码 并开启轮询
onBeforeMount(async () => {
  const qrCodeData = await getQrCode();
  if (qrCodeData.code === 20000) {
    qrCodeUrl.value = qrCodeData?.data.qrCodeUrl;
    ticket.value = qrCodeData.data.ticket;
  } else {
    await getWxQrCode();
    message(response.message, { type: "error" });
  }
});

// 轮询检查登录状态=>获取用户信息=>跳转首页
const checkLoginStatus = () => {
  checkLogin({
    ticket: ticket.value
  }).then(res => {
    if (res.code === 20000) {
      setToken({
        accessToken: res.data,
        refreshToken: res.data
      });
      getUserInfo(res.data);
      pause(); // 成功后停止轮询
    }
  });
};
const { pause } = useIntervalFn(checkLoginStatus, 2000, {
  immediate: true
});
// 获取用户信息
const getUserInfo = token => {
  useUserStoreHook()
    .login(token)
    .then(res => {
      if (res.code == 20000) {
        // 获取后端路由
        return initRouter().then(() => {
          router.push(getTopMenu(true).path).then(() => {
            // message(t("login.LoginSuccess"), { type: "success" });
          });
        });
      } else {
        removeToken();
        message(t("login.LoginFail"), { type: "error" });
      }
    });
};

onBeforeUnmount(() => {
  qrCodeUrl.value = "";
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      />
      <!-- 国际化 -->
      <el-dropdown trigger="click">
        <globalization
          class="hover:text-primary hover:!bg-[transparent] w-[20px] h-[20px] ml-1.5 cursor-pointer outline-none duration-300"
        />
        <template #dropdown>
          <el-dropdown-menu class="translation">
            <el-dropdown-item
              :style="getDropdownItemStyle(locale, 'zh')"
              :class="['dark:!text-white', getDropdownItemClass(locale, 'zh')]"
              @click="translationCh"
            >
              <IconifyIconOffline
                v-show="locale === 'zh'"
                class="check-zh"
                :icon="Check"
              />
              简体中文
            </el-dropdown-item>
            <!-- <el-dropdown-item
              :style="getDropdownItemStyle(locale, 'en')"
              :class="['dark:!text-white', getDropdownItemClass(locale, 'en')]"
              @click="translationEn"
            >
              <span v-show="locale === 'en'" class="check-en">
                <IconifyIconOffline :icon="Check" />
              </span>
              English
            </el-dropdown-item> -->
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>
          <Motion class="-mt-2 -mb-1">
            <img class="w-72 h-72" :src="qrCodeUrl" alt="登陆二维码 " />
          </Motion>
          <Motion>
            <el-divider>
              <p class="text-gray-500 text-xs" style="text-wrap: nowrap">
                {{ t("login.loginTip") }}
                <a
                  class="text-primary"
                  href="https://www.deptags.com/external/html/PrivacyAgreement.html"
                  target="_blank"
                  >隐私政策</a
                >和
                <a
                  class="text-primary"
                  href="https://www.deptags.com/external/html/ServiceAgreement.html"
                  target="_blank"
                  >服务协议</a
                >
              </p>
            </el-divider>
          </Motion>
        </div>
      </div>
      <div class="bottom-equity-bg">
        Copyright © 2024-present DepTags
        <a
          class="hover:text-primary"
          href="http://beian.miit.gov.cn"
          target="_blank"
        >
          &nbsp;{{ TITLE }}
          沪ICP备2024064542号-1
        </a>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.bottom-equity-bg {
  position: absolute;
  bottom: 0;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: right;
  width: 98%;
  height: 35px;
  padding-right: 40px;
  font-size: 12px;
  color: #6c7d8f;
}

.translation {
  ::v-deep(.el-dropdown-menu__item) {
    padding: 5px 40px;
  }

  .check-zh {
    position: absolute;
    left: 20px;
  }

  .check-en {
    position: absolute;
    left: 20px;
  }
}
</style>
